<?php
$working = true;
$url = "http://hdstudio.org/novinki_serialy_1/";
$i = 1;

ini_set("error_reporting",  "E_ALL & ~E_DEPRECATED & ~E_WARNING");
ini_set("log_errors", "Off");
ini_set("display_errors", "Off");

$db = new SQLite3("serials.db");
$db->exec('CREATE TABLE IF NOT EXISTS serials (title TEXT NOT NULL, date TEXT NOT NULL, genre TEXT NOT NULL, original TEXT NOT NULL, desc TEXT NOT NULL, link TEXT NOT NULL)');

while($working){
	if($i == 1){ $raw_page = file_get_contents($url); }
	else { $raw_page = file_get_contents($url."page/".$i."/"); }
	
	if( $http_response_header[0] == "HTTP/1.1 404 Not Found"){ $working = false; break; }
	
	$page = explode("\n", $raw_page);
	
	echo "[+] Обработка страницы {$i}\n";
	
	$raw_links = [ $page[129], $page[144], $page[159], $page[174], $page[189], $page[204], $page[219], $page[234], $page[249], $page[264], $page[279], $page[294] ];
	
	forEach($raw_links as $slink){
		if($slink == null){ continue; }
		$drop1 = explode('<a href="', $slink);
		$drop2 = explode('">', $drop1[1]);
		$link = $drop2[0];
		unset($drop1, $drop2);
		$serial = file_get_contents($link);
		$spage = explode("\n", $serial);
		
		
		echo "[+] Обработка {$link}\n";
		// title
		$title1 = explode("<span>", $spage[154]);
		$title2 = explode(" </span>", $title1[1]);
		$title = $title2[0];
		
		//date
		$date1 = explode("Дата выхода: <span>", $spage[210]);
		$date2 = explode("</span>", $date1[1]);
		$date = $date2[0];
		
		// genre
		$genre1 = explode('Жанр: <span itemprop="genre">', $spage[200]);
		$genre2 = explode("</span>", $genre1[1]);
		$genre = $genre2[0];
		
		// original
		$orig1 = explode("Оригинал: <span>", $spage[216]);
		$orig2 = explode("</span>", $orig1[1]);
		$orig = str_replace("'", "", $orig2[0]);
		
		// description
		$desc1 = explode('<article class="eText">', $spage[244]);
		$desc2 = explode('<a', $desc1[1]);
		$desc = str_replace(["<br>", "'"], [" ", " "], $desc2[0]);
		// link
		$link1 = explode('<iframe src="', $spage[281]);
		$link2 = explode('"', $link1[1]);
		$link = $link2[0];
		
		if($title == null or $date == null or $genre == null or $orig == null or $desc == null or $link == null){
			echo "[\e[1;31m!\e[0m] Данная ссылка была обработана не верно! Переход к следующей...\n";
			continue;
		}
		
		$db->exec("INSERT INTO serials (title, date, genre, original, desc, link) VALUES ('".$title."', '".$date."', '".$genre."', '".$orig."', '".$desc."', '".$link."')" );
		
	}
	$i++;
}

$db->close();
?>